package com.fenshi.manager.activity.car;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.location.Location;
import android.os.Bundle;
import android.os.PowerManager;
import android.support.v7.app.AlertDialog;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.LocationManagerProxy;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdate;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.LocationSource;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.CameraPosition;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.MarkerOptions;
import com.fenshi.manager.R;
import com.fenshi.presenter.imp.CurrentCarPresenterImp;
import com.fenshi.until.CookicUntil;
import com.fenshi.until.EvilTransform;
import com.fenshi.view.CurrentCarView;
import com.mikepenz.iconics.view.IconicsTextView;
import com.quickdv.activity.MapActivity;
import com.quickdv.until.AlertHelper;

import butterknife.InjectView;

public class CurrentCarActivity extends MapActivity implements LocationSource, AMapLocationListener, CurrentCarView {

    @InjectView(R.id.current_car_cast)
    IconicsTextView currentCarCast;
    @InjectView(R.id.current_car_status)
    LinearLayout currentCarStatus;
    private LocationManagerProxy mLocationManagerProxy;
    private OnLocationChangedListener mListener;

    private CurrentCarPresenterImp presenter;
    private ProgressDialog progressDialog;

    //    @InjectView(R.id.return_car)
//    public Button return_car;
    @InjectView(R.id.current_car_cast)
    public IconicsTextView current_car_cast;
    @InjectView(R.id.current_car_distance)
    public IconicsTextView current_car_distance;
    @InjectView(R.id.current_car_time)
    public IconicsTextView current_car_time;

    PowerManager powerManager = null;
    PowerManager.WakeLock wakeLock = null;


    @Override
    public void onResume() {
        super.onResume();
        wakeLock.acquire();
    }

    @Override
    public void onPause() {
        super.onPause();
        wakeLock.release();
    }

    @Override
    public int getLayoutID() {
        return R.layout.activity_current_car;
    }

    @Override
    public void initView() {
        powerManager = (PowerManager) this.getSystemService(this.POWER_SERVICE);
        wakeLock = this.powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, "My Lock");
        presenter.initViewAndEvent();
    }

    void onClick() {
        AlertDialog.Builder builder = new AlertDialog.Builder(CurrentCarActivity.this);
        builder.setTitle("提示").setMessage("确定归还当前使用车辆").setNegativeButton("归还", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
                presenter.vehicles();
            }
        }).setPositiveButton("不归还", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
            }
        }).create().show();

    }


    @Override
    public void initActionbar() {
        log.e("packageName", getPackageName());
    }

    @Override
    public void initData() {
        presenter = new CurrentCarPresenterImp(this);
        presenter.initViewAndEvent();
    }

    @Override
    protected void init() {

        super.init();
        setUpMap();
    }

    private void setUpMap() {
        aMap.setLocationSource(this);// 设置定位监听
        aMap.getUiSettings().setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        // 设置定位的类型为定位模式：定位（AMap.LOCATION_TYPE_LOCATE）、跟随（AMap.LOCATION_TYPE_MAP_FOLLOW）
        // 地图根据面向方向旋转（AMap.LOCATION_TYPE_MAP_ROTATE）三种模式
//        aMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);
    }

    LatLng latlng;

    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (amapLocation != null && amapLocation.getAMapException().getErrorCode() == 0) {
            //获取位置信息
            Double geoLat = amapLocation.getLatitude();
            Double geoLng = amapLocation.getLongitude();
            changeCamera(
                    CameraUpdateFactory.newCameraPosition(new CameraPosition(
                            new LatLng(geoLat, geoLng), aMap.getCameraPosition().zoom, 0, 30)), null);
            mListener.onLocationChanged(amapLocation);
        }
    }

    private void changeCamera(CameraUpdate update, AMap.CancelableCallback callback) {
        //初始化地图中心位置
        aMap.animateCamera(update, 1000, callback);
        aMap.clear();

        MarkerOptions options = new MarkerOptions().anchor(0.5f, 0.5f).icon(BitmapDescriptorFactory.fromResource(R.drawable.location_icon))
                .position(latlng)
                .draggable(true).period(10);
        aMap.addMarker(options);


    }

    @Override
    public void onLocationChanged(Location location) {

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }


    /**
     * 激活定位
     */
    @Override
    public void activate(OnLocationChangedListener listener) {
//        mListener = listener;
//        if (mLocationManagerProxy == null) {
//            mLocationManagerProxy = LocationManagerProxy.getInstance(this);
//            //此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
//            //注意设置合适的定位时间的间隔，并且在合适时间调用removeUpdates()方法来取消定位请求
//            //在定位结束后，在合适的生命周期调用destroy()方法
//            //其中如果间隔时间为-1，则定位只定一次
//            mLocationManagerProxy.requestLocationData(
//                    LocationProviderProxy.AMapNetwork, 60 * 1000, 15, this);
//        }
    }

    /**
     * 停止定位
     */
    @Override
    public void deactivate() {
        mListener = null;
        if (mLocationManagerProxy != null) {
            mLocationManagerProxy.removeUpdates(this);
            mLocationManagerProxy.destroy();
        }
        mLocationManagerProxy = null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        deactivate();
        presenter.stop();
    }



    @Override
    public void initViewAndEvent() {
        // Handle Toolbar
        mapView = findView(R.id.map);

        if (getIntent().getExtras() != null) {
            String from = getIntent().getExtras().getString(CookicUntil.FROM);
            if (from != null) ;
//                return_car.setVisibility(View.GONE);
        }

        progressDialog = new AlertHelper(this).LoadingAlert();
        presenter.start();
    }

    @Override
    public void refreshInfo(JSONObject info) {


        current_car_cast.setText("{faw-cny}" + String.format("%.2f",Float.valueOf(info.getString("money"))) + "元");

        current_car_distance.setText("{faw-car}" + info.getFloat("distance") + "公里");
        current_car_time.setText("{faw-clock-o}" + info.getInteger("wieldTime") / 60 + "小时");

        int time = info.getInteger("wieldTime");
        if (time> 60){
            int hour = time/60;
            int month = time%60;
            current_car_time.setText("{faw-clock-o}" + hour+ "小时" + month + "分钟");
        }else
            current_car_time.setText("{faw-clock-o}" + info.getInteger("wieldTime")+ "分钟");

        Double geoLat = Double.valueOf(info.getString("lat"));
        Double geoLng = Double.valueOf(info.getString("lng"));
        double[] latlngs = EvilTransform.transform(geoLat, geoLng);

        if (latlngs != null && latlngs.length > 1) {
            latlng = new LatLng(latlngs[0], latlngs[1]);
            changeCamera(
                    CameraUpdateFactory.newCameraPosition(new CameraPosition(
                            latlng, 18, 0, 30)), null);
        }else
            showError("车辆定位失败");
    }

    @Override
    public void returnCar() {
        AlertDialog alertDialog = new AlertDialog.Builder(CurrentCarActivity.this)
                .setTitle("提示").setMessage("车辆归还成功").setNegativeButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                        finish();
                    }
                }).setCancelable(false).create();
        alertDialog.show();

    }

    @Override
    public void dismissRutrunButton(boolean disable) {
//        return_car.setClickable(disable);
    }

    @Override
    public void showLoad() {
        if (progressDialog != null) progressDialog.show();
    }

    @Override
    public void dismissLoad() {
        if (progressDialog != null && progressDialog.isShowing()) progressDialog.dismiss();
    }

    @Override
    public void setStatusVisibale(int visibale) {
        currentCarStatus.setVisibility(visibale);
    }

    @Override
    public void showError(String error) {
        Toast.makeText(this, error, Toast.LENGTH_LONG).show();
    }
}
